from rest_framework import serializers
from ..models import Category

class CategorySerializer(serializers.ModelSerializer):
    """分类序列化器"""
    documents_count = serializers.SerializerMethodField()

    class Meta:
        model = Category
        fields = ['id', 'title', 'slug', 'description', 'parent', 'is_nav', 'nav_sort', 'documents_count']
    
    def get_documents_count(self, obj):
        """获取文档数量"""
        return getattr(obj, 'documents_count', 0)

class CategoryDetailSerializer(serializers.ModelSerializer):
    """分类详情序列化器"""
    parent = CategorySerializer(read_only=True)
    documents_count = serializers.SerializerMethodField()
    
    class Meta:
        model = Category
        fields = ['id', 'title', 'slug', 'description', 'parent', 'is_nav', 'nav_sort', 'documents_count']
    
    def get_documents_count(self, obj):
        """获取文档数量"""
        return getattr(obj, 'documents_count', 0)

class CategoryNavSerializer(serializers.ModelSerializer):
    """导航分类序列化器"""
    children = serializers.SerializerMethodField()

    class Meta:
        model = Category
        fields = ['id', 'title', 'slug', 'nav_sort', 'nav_path', 'nav_icon', 'children']

    def get_children(self, obj):
        """获取子分类"""
        children = Category.objects.filter(parent=obj).order_by('nav_sort')
        return CategoryNavSerializer(children, many=True).data

class CategoryTreeSerializer(serializers.ModelSerializer):
    """分类树序列化器"""
    children = serializers.SerializerMethodField()
    
    class Meta:
        model = Category
        fields = ['id', 'title', 'slug', 'nav_sort', 'children']
    
    def get_children(self, obj):
        """获取子分类"""
        children = Category.objects.filter(parent=obj).order_by('nav_sort')
        serializer = CategoryTreeSerializer(children, many=True)
        return serializer.data 